package com.shiyipicture.shiyipicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiyipicture.shiyipicturebackend.enums.SpaceLevelEnum;
import com.shiyipicture.shiyipicturebackend.enums.SpaceRoleEnum;
import com.shiyipicture.shiyipicturebackend.enums.SpaceTypeEnum;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.exception.ThrowUtils;
import com.shiyipicture.shiyipicturebackend.model.dto.spaceUser.SpaceUserAddRequest;
import com.shiyipicture.shiyipicturebackend.model.dto.spaceUser.SpaceUserQueryRequest;
import com.shiyipicture.shiyipicturebackend.model.entity.Space;
import com.shiyipicture.shiyipicturebackend.model.entity.SpaceUser;
import com.shiyipicture.shiyipicturebackend.model.entity.User;
import com.shiyipicture.shiyipicturebackend.model.vo.SpaceUserVO;
import com.shiyipicture.shiyipicturebackend.model.vo.SpaceVO;
import com.shiyipicture.shiyipicturebackend.model.vo.UserVO;
import com.shiyipicture.shiyipicturebackend.service.SpaceService;
import com.shiyipicture.shiyipicturebackend.service.SpaceUserService;
import com.shiyipicture.shiyipicturebackend.mapper.SpaceUserMapper;
import com.shiyipicture.shiyipicturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
 * @createDate 2025-02-20 15:08:21
 */
@Service
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
  implements SpaceUserService {
  @Resource
  private SpaceService spaceService;

  @Resource
  private UserService userService;

  /**
   * 校验空间角色对象
   *
   * @param spaceUser
   * @param add
   */
  @Override
  public void validSpaceUser(SpaceUser spaceUser, boolean add) {
    ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
    Long spaceId = spaceUser.getSpaceId();
    Long userId = spaceUser.getUserId();
    if (add) {
      ThrowUtils.throwIf(ObjectUtil.hasEmpty(spaceId, userId), ErrorCode.PARAMS_ERROR);
      Space space = spaceService.getById(spaceId);
      ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
      User user = userService.getById(userId);
      ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
    }
    String spaceRole = spaceUser.getSpaceRole();
    SpaceRoleEnum spaceRoleEnum = SpaceRoleEnum.getEnumByValue(spaceRole);
    if (spaceRole != null && spaceRoleEnum == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间角色不存在");
    }
  }

  /**
   * 添加空间角色关系
   *
   * @param spaceUserAddRequest
   * @param loginUser
   * @return
   */
  @Override
  public long addSpaceUser(SpaceUserAddRequest spaceUserAddRequest, User loginUser) {
    ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);
    SpaceUser spaceUser = new SpaceUser();
    BeanUtils.copyProperties(spaceUserAddRequest, spaceUser);
    validSpaceUser(spaceUser, true);
    boolean save = this.save(spaceUser);
    ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
    return spaceUser.getId();
  }

  /**
   * 返回查找空间角色Wrapper
   *
   * @param spaceUserQueryRequest
   * @return
   */
  @Override
  public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
    QueryWrapper<SpaceUser> spaceUserQueryWrapper = new QueryWrapper<>();
    Long id = spaceUserQueryRequest.getId();
    Long spaceId = spaceUserQueryRequest.getSpaceId();
    Long userId = spaceUserQueryRequest.getUserId();
    String spaceRole = spaceUserQueryRequest.getSpaceRole();
    spaceUserQueryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
    spaceUserQueryWrapper.eq(ObjectUtil.isNotEmpty(spaceId), "spaceId", spaceId);
    spaceUserQueryWrapper.eq(ObjectUtil.isNotEmpty(userId), "userId", userId);
    spaceUserQueryWrapper.eq(ObjectUtil.isNotEmpty(spaceRole), "spaceRole", spaceRole);
    return spaceUserQueryWrapper;
  }

  /**
   * 查询封装类
   * @param spaceUser
   * @param request
   * @return
   */
  @Override
  public SpaceUserVO getSpaceUserVO(SpaceUser spaceUser, HttpServletRequest request) {
    SpaceUserVO spaceUserVO = SpaceUserVO.objToVo(spaceUser);
    Long userId = spaceUser.getUserId();
    if (userId != null && userId > 0) {
      User user = userService.getById(userId);
      UserVO userVo = userService.getUserVo(user);
      spaceUserVO.setUser(userVo);
    }
    //关联查询空间信息
    Long spaceId = spaceUser.getSpaceId();
    if (spaceId != null && spaceId > 0) {
      Space space = spaceService.getById(spaceId);
      SpaceVO spaceVo = spaceService.getSpaceVo(space, request);
      spaceUserVO.setSpace(spaceVo);
    }
    return spaceUserVO;
  }


  /**
   * 查询封装类列表
   * @param spaceUserList
   * @return
   */
  @Override
  public List<SpaceUserVO> getSpaceUserVOList(List<SpaceUser> spaceUserList) {
    // 判断输入列表是否为空
    if (CollUtil.isEmpty(spaceUserList)) {
      return Collections.emptyList();
    }
    // 对象列表 => 封装对象列表
    List<SpaceUserVO> spaceUserVOList = spaceUserList.stream().map(SpaceUserVO::objToVo).collect(Collectors.toList());
    // 1. 收集需要关联查询的用户 ID 和空间 ID
    Set<Long> userIdSet = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toSet());
    Set<Long> spaceIdSet = spaceUserList.stream().map(SpaceUser::getSpaceId).collect(Collectors.toSet());
    // 2. 批量查询用户和空间
    Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
      .collect(Collectors.groupingBy(User::getId));
    Map<Long, List<Space>> spaceIdSpaceListMap = spaceService.listByIds(spaceIdSet).stream()
      .collect(Collectors.groupingBy(Space::getId));
    // 3. 填充 SpaceUserVO 的用户和空间信息
    spaceUserVOList.forEach(spaceUserVO -> {
      Long userId = spaceUserVO.getUserId();
      Long spaceId = spaceUserVO.getSpaceId();
      // 填充用户信息
      User user = null;
      if (userIdUserListMap.containsKey(userId)) {
        user = userIdUserListMap.get(userId).get(0);
      }
      spaceUserVO.setUser(userService.getUserVo(user));
      // 填充空间信息
      Space space = null;
      if (spaceIdSpaceListMap.containsKey(spaceId)) {
        space = spaceIdSpaceListMap.get(spaceId).get(0);
      }
      spaceUserVO.setSpace(SpaceVO.objToVo(space));
    });
    return spaceUserVOList;
  }

}




